<template>
  
  <div class="sign-in-container">
    <h2>每日签到</h2>

    <!-- 加载状态 -->
    <div v-if="loading">加载中...</div>

    <!-- 用户信息 -->
  <div v-else-if="userInfo">
  <div class="user-info">
    <p><strong>用户ID：</strong>{{ userInfo.ID }}</p>
    <p><strong>用户等级：</strong>{{ userInfo.level }}</p>
  </div>

       <el-button type="primary" @click="handleSignIn" :disabled="isSignedIn" class="sign-in-button">
    {{ isSignedIn ? '已签到' : '立即签到' }}
  </el-button>

      <div v-if="signInSuccess" class="success-message">
        签到成功！+10 积分
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-else class="error-message">
      无法加载用户信息，请检查登录状态。
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import axios from '../axios'
import { ElMessage } from 'element-plus'

interface UserInfo {
  ID: number;
  username: string;
  level: number;
}


const userInfo = ref<UserInfo | null>(null)
const loading = ref(true)
const isSignedIn = ref(false)
const signInSuccess = ref(false)

// 从后端获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await axios.get('/api/users/me');
    userInfo.value = response.data
  } catch (error) {
    console.error('获取用户信息失败:', error);
    userInfo.value = null;
  } finally {
    loading.value = false;
  }
}
// 签到逻辑
const handleSignIn = async () => {
  try {
    const response = await axios.post('/api/users/me/checkin') // 使用正确的API路径
    console.log('签到成功:', response.data)
    isSignedIn.value = true
    signInSuccess.value = true

    setTimeout(() => {
      signInSuccess.value = false
    }, 3000)
  } catch (error) {
    console.error('签到失败:', error)
    ElMessage.error('签到失败，请重试')
  }
}

// 页面加载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.sign-in-container {
  max-width: 400px;
  margin: 50px auto;
  padding: 30px;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.user-info {
  margin-bottom: 20px;
}

.user-info p {
  font-size: 16px;
  color: #333;
}

.sign-in-button {
  width: 100%;
  padding: 12px;
  font-size: 16px;
  border-radius: 8px;
}

.success-message {
  margin-top: 20px;
  color: green;
  font-weight: bold;
  animation: fadeInOut 3s ease-in-out;
}

@keyframes fadeInOut {
  0% { opacity: 0; }
  10% { opacity: 1; }
  90% { opacity: 1; }
  100% { opacity: 0; }
}
</style>